﻿/*
 * @autor: hectorea
 * @date: 24/07/12
 * @project: SwappingNumbers
 */

using System;

namespace SwappingNumbers
{
    /// <summary>
    /// Swapping of 2 numbers without using a 3rd variable. 
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please type the first number: ");
            string first = Console.ReadLine();
            Console.Write("Please type the second number: ");
            string second = Console.ReadLine();

            int a = int.Parse(first);
            int b = int.Parse(second);
            //Swap(ref a, ref b);

            SwapNumbers(ref a, ref b);


            Console.Write(string.Format("The swapped values are a:{0} and b:{1}", a, b));

            Console.WriteLine(string.Empty);
            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

        /// <summary>
        /// Using bitwise operations (XOR)
        /// </summary>
        /// <param name="a">Integer Value</param>
        /// <param name="b">Integer Value</param>
        private static void Swap(ref int a, ref int b)
        {
            a ^= b;
            b ^= a;
            a ^= b;
        }

        /// <summary>
        /// Using simple addition and subtraction operations
        /// </summary>
        /// <param name="a">Interger Value</param>
        /// <param name="b">Integer Value</param>
        private static void SwapNumbers(ref int a, ref int b)
        {
            a = a + b;  //Stores temporally the value of b in a
            b = a - b;  //Removes the value of b and we get the value of a in b
            a = a - b;  //Removes the value of a and we get the value of b in a
                        // Got it? A little bit tricky, he?
        }            
    }
}
